package com.yueyang.sojourn.server.validation;

import com.yueyang.sojourn.server.validation.annotation.DateFormat;
import org.apache.commons.lang3.time.DateUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.ParseException;
import java.util.Date;

/**
 * @author yemingxing
 * @summary
 * @Copyright (c) 2020, Yueyang Group All Rights Reserved.
 * @since 2020-02-18
 */
public class DateFormatValidator implements ConstraintValidator<DateFormat, String> {

    private DateFormat dateFormat;

    @Override
    public void initialize(DateFormat constraintAnnotation) {
        this.dateFormat = constraintAnnotation;
    }

    @Override
    public boolean isValid(String string, ConstraintValidatorContext constraintValidatorContext) {
        try {
            if (string == null || string.length() == 0) {
                return true;
            }
            Date date = DateUtils.parseDate(string, dateFormat.format());
            if (dateFormat.isFuture()) {
                constraintValidatorContext.disableDefaultConstraintViolation();
                //重新添加错误提示语句
                constraintValidatorContext
                        .buildConstraintViolationWithTemplate(dateFormat.fieldCN() + "需晚于当前日期").addConstraintViolation();
                return date.after(new Date());
            }
            return true;
        } catch (ParseException e) {
            return false;
        }
    }
}
